//
//  XTXTool.m
//  XBra
//
//  Created by 余清巍 on 2017/2/20.
//  Copyright © 2017年 余清巍. All rights reserved.
//

#import "XTXTool.h"
#import <CommonCrypto/CommonCryptor.h>
//#import "LMNoticeLabel.h"
NSString *const kInitVector = @"16-Bytes--String";
size_t const suzusnsk = kCCKeySizeAES128;
@implementation XTXTool

+ (instancetype)share{
    static XTXTool *aValue = nil;
    if (!aValue) {
        aValue = [[XTXTool alloc]init];
    }
    return aValue;
}

//后台AES加密
+ (NSString *)encryptAES:(NSDictionary *)dict key:(NSString *)key {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        //NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    NSData *contentData = [mutStr dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = contentData.length;
    // 为结束符'\\0' +1
    char keyPtr[suzusnsk + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    // 密文长度 <= 明文长度 + BlockSize
    size_t encryptSize = dataLength + kCCBlockSizeAES128;
    void *encryptedBytes = malloc(encryptSize);
    size_t actualOutSize = 0;
    NSData *initVector = [kInitVector dataUsingEncoding:NSUTF8StringEncoding];
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES,
                                          kCCOptionPKCS7Padding,  // 系统默认使用 CBC，然后指明使用 PKCS7Padding
                                          keyPtr,
                                          suzusnsk,
                                          initVector.bytes,
                                          contentData.bytes,
                                          dataLength,
                                          encryptedBytes,
                                          encryptSize,
                                          &actualOutSize);
    if (cryptStatus == kCCSuccess) {
        // 对加密后的数据进行 base64 编码
        NSData *data= [[[NSData dataWithBytesNoCopy:encryptedBytes length:actualOutSize] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed] dataUsingEncoding:NSUTF8StringEncoding];
        if (!data || [data length] == 0) {
            return @"";
        }
        NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
        [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
            unsigned char *dataBytes = (unsigned char*)bytes;
            for (NSInteger i = 0; i < byteRange.length; i++) {
                NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
                if ([hexStr length] == 2) {
                    [string appendString:hexStr];
                } else {
                    [string appendFormat:@"0%@", hexStr];
                }
            }
        }];
        return string;
    }
    free(encryptedBytes);
    return nil;
}

//存档
+(void)archive:(id)ConsumerModel{
    NSMutableData *data = [NSMutableData data];
    // 归档类.
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    // 开始归档（@"model" 是key值，也就是通过这个标识来找到写入的对象）.
    [archiver encodeObject:ConsumerModel forKey:@"model"];
    // 归档结束.
    [archiver finishEncoding];
    // 写入本地（@"weather" 是写入的文件名）.
    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"weather"];
    [data writeToFile:file atomically:YES];
}
+(void)showError:(NSString *)error{
    [self show:error];
}
+(void)showSuccess:(NSString *)success{
    [self show:success];
}
+(void)show:(NSString *)str{
    dispatch_async(dispatch_get_main_queue(), ^{
        MBProgressHUD *Hud=[MBProgressHUD showHUDAddedTo:UIApplication.sharedApplication.keyWindow animated:YES];
        Hud.mode=MBProgressHUDModeCustomView;
        [Hud.label setFont:[UIFont systemFontOfSize:12]];
        Hud.label.text=str;
        [Hud hideAnimated:YES afterDelay:2.f];
    });
    
}

@end
